package org.ring.common.transport;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import org.ring.common.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;

/**
 * @since 2023-10-28 11:47
 */
public class ClientTransport {

    private static final Logger logger = LoggerFactory.getLogger(ClientTransport.class);

    private final TransportConfig transportConfig;

    private ConnectionManager connectionManager = new ConnectionManager();
    private DefaultMessageHandlerRegistry handlerRegistry ;


    public ClientTransport handlerRegistry(DefaultMessageHandlerRegistry handlerRegistry){
        this.handlerRegistry = handlerRegistry;
        return this;
    }

    public ClientTransport(TransportConfig transportConfig) {
        this.transportConfig = transportConfig;
    }


    public Connection connect(URL url) {
        int connectTimeoutMillis = 1000;
        NettyClientHandler clientHandler = new NettyClientHandler();

        Bootstrap bootstrap = new Bootstrap()
            .group(eventLoopGroup().next())
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {

                    Codec codec = Codec.EXTENSION_LOADER.getExtension(url.getProtocol());
                    ChannelPipeline pipeline = ch.pipeline();

                    pipeline.addLast(new NettyEncoder(codec));
                    pipeline.addLast(new NettyDecoder(codec));
                    pipeline.addLast(clientHandler);
                }
            });

        try {
            String host = url.getHost();
            int port = url.getPort();
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            logger.info("connected get future!");
            Channel channel = channelFuture.channel();
            Connection connection = new NettyClientConnection(channel);
            return connection;
        } catch (InterruptedException e) {
            //TODO RemotingException
            throw new RuntimeException(e);
        } catch (Throwable e){
            //TODO RemotingException
            throw new RuntimeException(e);
        }
    }

    class NettyClientHandler extends ChannelDuplexHandler {

        private Connection connection;

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            Message message = (Message) msg;
            if(message.isRequest()){
                message.markResponse();

                Object request = message.getData();

                MessageHandler messageHandler = handlerRegistry.lookup(message);

                Channel channel = ctx.channel();
                CompletableFuture future = messageHandler.handle(connection,request);

                future.whenComplete((r,t)-> {
                    message.setData(r);
                    //channel.write(message);
                    channel.writeAndFlush(message);
                    //ctx.writeAndFlush(message);
                });
            } else {
                CompletableFuture completableFuture = RpcCompletableFuture.removeFuture(message);
                if(completableFuture != null){
                    completableFuture.complete(((Message) msg).getData());
                }
            }
        }



        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            logger.info("==========client handlerAdded");
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            connectionManager.remove(connection);
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            logger.info("==========client active");
            Connection connection = new NettyClientConnection(ctx.channel());
            this.connection = connectionManager.addConnection(connection);
        }

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if(logger.isDebugEnabled()){
                logger.debug("write ==> {}",msg);
            }
            super.write(ctx, msg, promise);
        }

    }

    private EventLoopGroup eventLoopGroup() {
        return new NioEventLoopGroup();
    }

}
